package com.whmskj.xjlhbc.mobile.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.mapper.*;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Tag(name = "数据汇报",description = "进度汇报")
@RequestMapping("/sjhb")
public class SjhbController {

    @Autowired
    private Bchb01zjrhbMapper bchb01zjrhbMapper;

    @Autowired
    private Bchb02jsrhbMapper bchb02jsrhbMapper;

    @Autowired
    private Bchb02jsrhbzbMapper bchb02jsrhbzbMapper;

    @Autowired
    private Bchb04czrhbMapper bchb04czrhbMapper;

    @Autowired
    private Bchb04czrhbzbMapper bchb04czrhbzbMapper;

    @Autowired
    private Bchb05dmjzcrkMapper bchb05dmjzcrkMapper;

    /**
     * 整经日报列表
     */
    @GetMapping("/zjList")
    @Operation(description = "整经日报列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult zjList(Bchb01zjrhb param){
        Page.startPage();
        LambdaQueryWrapper<Bchb01zjrhb> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(param.getJtnum()), Bchb01zjrhb::getJtnum, param.getJtnum());
        wrapper.like(StringUtils.hasText(param.getZjname()), Bchb01zjrhb::getZjname, param.getZjname());
        wrapper.like(StringUtils.hasText(param.getPhnum()), Bchb01zjrhb::getPhnum, param.getPhnum());
        wrapper.ge(StringUtils.hasText(param.getStartDate()), Bchb01zjrhb::getStartDate, param.getStartDate());
        wrapper.le(StringUtils.hasText(param.getEndDate()), Bchb01zjrhb::getEndDate, param.getEndDate());
        wrapper.orderByDesc(Bchb01zjrhb::getId);
        List<Bchb01zjrhb> list = bchb01zjrhbMapper.selectList(wrapper);
        return Page.getDataTable(list);
    }

    /**
     * 整经日报详情
     */
    @GetMapping("/zjDetailById")
    @Operation(description = "整经日报详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult zjDetailById(Long id){
        Bchb01zjrhb bchb01zjrhb = bchb01zjrhbMapper.selectById(id);
        return AjaxResult.success(bchb01zjrhb);
    }

    /**
     * 提交/编辑整经日报
     */
    @PostMapping("/saveUpdateZj")
    @Operation(description = "整经日报提交")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult saveUpdateZj(@RequestBody Bchb01zjrhb body){
        Long id = body.getId();
        body.setFillingTime(DateUtil.now());
        body.setReporter(getName());
        int result = Objects.nonNull(id) ? bchb01zjrhbMapper.updateById(body) : bchb01zjrhbMapper.insert(body);
        return AjaxResult.success(result>0);
    }

    /**
     * 删除整经日报
     */
    @PostMapping("/deleteZj/{id}")
    @Operation(description = "整经日报删除")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult deleteZj(@PathVariable Long id){
        int result = bchb01zjrhbMapper.deleteById(id);
        return AjaxResult.success(result>0);
    }



    /**
     * 浆纱日报列表
     */
    @GetMapping("/jsList")
    @Operation(description = "浆纱日报列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult jsList(Bchb02jsrhb param){
        Page.startPage();
        LambdaQueryWrapper<Bchb02jsrhb> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(param.getJtnum()), Bchb02jsrhb::getJtnum, param.getJtnum());
        wrapper.like(StringUtils.hasText(param.getPhnum()), Bchb02jsrhb::getPhnum, param.getPhnum());
        wrapper.like(StringUtils.hasText(param.getClasses()), Bchb02jsrhb::getClasses, param.getClasses());
        wrapper.ge(StringUtils.hasText(param.getStartDate()), Bchb02jsrhb::getStartDate, param.getStartDate());
        wrapper.le(StringUtils.hasText(param.getEndDate()), Bchb02jsrhb::getEndDate, param.getEndDate());
        wrapper.orderByDesc(Bchb02jsrhb::getId);
        List<Bchb02jsrhb> list = bchb02jsrhbMapper.selectList(wrapper);
        List<Bchb02jsrhbzb> allPzList = bchb02jsrhbzbMapper.selectList(null);
        list.forEach(item->{
            List<Bchb02jsrhbzb> pzList = allPzList.stream().filter(f -> f.getGlzbzd().equals(item.getId())).collect(Collectors.toList());
            item.setPzList(pzList);
        });
        return Page.getDataTable(list);
    }

    /**
     * 浆纱日报详情
     */
    @GetMapping("/jsDetailById")
    @Operation(description = "浆纱日报详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult jsDetailById(Long id){
        Bchb02jsrhb bchb02jsrhb = bchb02jsrhbMapper.selectById(id);
        LambdaQueryWrapper<Bchb02jsrhbzb> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bchb02jsrhbzb::getGlzbzd, id);
        List<Bchb02jsrhbzb> pzList = bchb02jsrhbzbMapper.selectList(wrapper);
        bchb02jsrhb.setPzList(pzList);
        return AjaxResult.success(bchb02jsrhb);
    }

    /**
     * 提交/编辑浆纱日报
     */
    @PostMapping("/saveUpdateJs")
    @Operation(description = "浆纱日报提交")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult saveUpdateJs(@RequestBody Bchb02jsrhb body){
        Long id = body.getId();
        if(Objects.nonNull(id)){
            LambdaQueryWrapper<Bchb02jsrhbzb> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Bchb02jsrhbzb::getGlzbzd, id);
            bchb02jsrhbzbMapper.delete(wrapper);
        }
        List<Bchb02jsrhbzb> pzList = body.getPzList();
        List<String> phList = pzList.stream().map(Bchb02jsrhbzb::getPhnum).distinct().collect(Collectors.toList());
        String phnum = StringUtils.collectionToCommaDelimitedString(phList);
        body.setPhnum(phnum);
        body.setReporter(getName());
        body.setFillingTime(DateUtil.now());
        int result = Objects.nonNull(id) ? bchb02jsrhbMapper.updateById(body) : bchb02jsrhbMapper.insert(body);
        pzList.forEach(pz->{
            pz.setTjdate(body.getTjDate());
            pz.setClasses(body.getClasses());
            pz.setJtnum(body.getJtnum());
            pz.setGlzbzd(body.getId());
            bchb02jsrhbzbMapper.insert(pz);
        });
        return AjaxResult.success(result>0);
    }

    /**
     * 删除浆纱日报
     */
    @PostMapping("/deleteJs/{id}")
    @Operation(description = "浆纱日报删除")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult deleteJs(@PathVariable Long id){
        LambdaQueryWrapper<Bchb02jsrhbzb> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bchb02jsrhbzb::getGlzbzd, id);
        bchb02jsrhbzbMapper.delete(wrapper);
        int result = bchb02jsrhbMapper.deleteById(id);
        return AjaxResult.success(result>0);
    }


    /**
     * 穿轴日报列表
     */
    @GetMapping("/czList")
    @Operation(description = "穿轴日报列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult czList(Bchb04czrhb param){
        Page.startPage();
        LambdaQueryWrapper<Bchb04czrhb> wrapper = new LambdaQueryWrapper<>();
        wrapper.gt(Objects.nonNull(param.getTotal190()) && param.getTotal190()>0, Bchb04czrhb::getTotal190, 0);
        wrapper.gt(Objects.nonNull(param.getTotal230()) && param.getTotal230()>0, Bchb04czrhb::getTotal230, 0);
        wrapper.like(StringUtils.hasText(param.getPhnum()), Bchb04czrhb::getPhnum, param.getPhnum());
        wrapper.ge(StringUtils.hasText(param.getStartDate()), Bchb04czrhb::getStartDate, param.getStartDate());
        wrapper.le(StringUtils.hasText(param.getEndDate()), Bchb04czrhb::getEndDate, param.getEndDate());
        wrapper.orderByDesc(Bchb04czrhb::getId);
        List<Bchb04czrhb> list = bchb04czrhbMapper.selectList(wrapper);
        List<Bchb04czrhbzb> allPzList = bchb04czrhbzbMapper.selectList(null);
        list.forEach(item->{
            List<Bchb04czrhbzb> pzList = allPzList.stream().filter(f -> f.getGlzbid().equals(item.getId())).collect(Collectors.toList());
            item.setPzList(pzList);
        });
        return Page.getDataTable(list);
    }

    /**
     * 浆纱日报详情
     */
    @GetMapping("/czDetailById")
    @Operation(description = "浆纱日报详情")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult czDetailById(Long id){
        Bchb04czrhb bchb04czrhb = bchb04czrhbMapper.selectById(id);
        LambdaQueryWrapper<Bchb04czrhbzb> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bchb04czrhbzb::getGlzbid, id);
        List<Bchb04czrhbzb> pzList = bchb04czrhbzbMapper.selectList(wrapper);
        bchb04czrhb.setPzList(pzList);
        return AjaxResult.success(bchb04czrhb);
    }

    /**
     * 提交/编辑穿轴日报
     */
    @PostMapping("/saveUpdateCz")
    @Operation(description = "穿轴日报提交")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult saveUpdateCz(@RequestBody Bchb04czrhb body){
        Long id = body.getId();
        if(Objects.nonNull(id)){
            LambdaQueryWrapper<Bchb04czrhbzb> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Bchb04czrhbzb::getGlzbid, id);
            bchb04czrhbzbMapper.delete(wrapper);
        }
        List<Bchb04czrhbzb> pzList = body.getPzList();
        long total190 = pzList.stream().filter(f -> f.getGgsize().equals("190")).mapToLong(Bchb04czrhbzb::getCzsnum).sum();
        long total230 = pzList.stream().filter(f -> f.getGgsize().equals("230")).mapToLong(Bchb04czrhbzb::getCzsnum).sum();
        List<String> phList = pzList.stream().map(Bchb04czrhbzb::getPhnum).distinct().collect(Collectors.toList());
        String phnum = StringUtils.collectionToCommaDelimitedString(phList);
        body.setPhnum(phnum);
        body.setTotal190(total190);
        body.setTotal230(total230);
        body.setReporter(getName());
        body.setFillingTime(DateUtil.now());
        int result = Objects.nonNull(id) ? bchb04czrhbMapper.updateById(body) : bchb04czrhbMapper.insert(body);
        pzList.forEach(pz->{
            pz.setTjdate(body.getTjdate());
            pz.setGlzbid(body.getId());
            bchb04czrhbzbMapper.insert(pz);
        });
        return AjaxResult.success(result>0);
    }

    /**
     * 删除穿轴日报
     */
    @PostMapping("/deleteCz/{id}")
    @Operation(description = "浆纱穿轴删除")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    @Transactional
    public AjaxResult deleteCz(@PathVariable Long id){
        LambdaQueryWrapper<Bchb04czrhbzb> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bchb04czrhbzb::getGlzbid, id);
        bchb04czrhbzbMapper.delete(wrapper);
        int result = bchb04czrhbMapper.deleteById(id);
        return AjaxResult.success(result>0);
    }


    /**
     * 地面经轴
     */
    @GetMapping("/dmjzList")
    @Operation(description = "地面经轴")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult dmjzList(){
        LambdaQueryWrapper<Bchb05dmjzcrk> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(Bchb05dmjzcrk::getCashier).isNull(Bchb05dmjzcrk::getTimeOfRelease);
        List<Bchb05dmjzcrk> dmjzList = bchb05dmjzcrkMapper.selectList(wrapper);
        List<Bchb05dmjzcrk> list190 = dmjzList.stream().filter(f -> "190".equals(f.getGgsize())).collect(Collectors.toList());
        List<Bchb05dmjzcrk> list230 = dmjzList.stream().filter(f -> "230".equals(f.getGgsize())).collect(Collectors.toList());
        long count190 = list190.size();
        long count230 = list230.size();
        long count = count190 + count230;

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> topMap = new HashMap<>();
        topMap.put("count", count);
        topMap.put("count190", count190);
        topMap.put("count230", count230);
        resultMap.put("top", topMap);
        List<Map<String, List<Map<String,Object>>>> list = new ArrayList<>();
        Map<String, List<Bchb05dmjzcrk>> map190 = list190.stream().collect(Collectors.groupingBy(Bchb05dmjzcrk::getPhnum));
        Map<String, List<Bchb05dmjzcrk>> map230 = list230.stream().collect(Collectors.groupingBy(Bchb05dmjzcrk::getPhnum));
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        Set<Map.Entry<String, List<Bchb05dmjzcrk>>> entries = map190.entrySet();
        Set<Map.Entry<String, List<Bchb05dmjzcrk>>> entries230 = map230.entrySet();
        List<Map<String, Object>> listMap190 = new ArrayList<>();
        List<Map<String, Object>> listMap230 = new ArrayList<>();
        for(Map.Entry<String, List<Bchb05dmjzcrk>> entry : entries){
            Map<String, Object> m = new HashMap<>();
            m.put("ph", entry.getKey());
            m.put("total", entry.getValue().size());
            listMap190.add(m);
        }
        for(Map.Entry<String, List<Bchb05dmjzcrk>> entry : entries230){
            Map<String, Object> m = new HashMap<>();
            m.put("ph", entry.getKey());
            m.put("total", entry.getValue().size());
            listMap230.add(m);
        }
        map.put("jz190", listMap190);
        map.put("jz230", listMap230);
        list.add(map);
        resultMap.put("list", list);
        return AjaxResult.success(resultMap);
    }

    /**
     * 地面经轴数据保存
     */
    @PostMapping("saveDmjz")
    @Operation(description = "地面经轴数据保存")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult saveDmjz(@RequestBody Bchb05dmjzcrk body){
        body.setRepository(getName());
        body.setBankingTime(DateUtil.now());
        int result = bchb05dmjzcrkMapper.insert(body);
        return AjaxResult.success(result>0);
    }

    /**
     * 地面经轴出库
     */
    @PostMapping("dmjzCk")
    @Operation(description = "地面经轴出库")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult dmjzCk(@RequestBody Bchb05dmjzcrk body){
        String phnum = body.getPhnum();
        LambdaQueryWrapper<Bchb05dmjzcrk> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bchb05dmjzcrk::getPhnum, phnum)
                .isNull(Bchb05dmjzcrk::getCashier).isNull(Bchb05dmjzcrk::getTimeOfRelease)
                .orderByDesc(Bchb05dmjzcrk::getBankingTime).last("limit 1");
        Bchb05dmjzcrk bchb05dmjzcrk = bchb05dmjzcrkMapper.selectOne(wrapper);
        if(Objects.isNull(bchb05dmjzcrk)){
            return AjaxResult.error();
        }
        bchb05dmjzcrk.setCashier(getName());
        bchb05dmjzcrk.setTimeOfRelease(DateUtil.now());
        int result = bchb05dmjzcrkMapper.updateById(bchb05dmjzcrk);
        return AjaxResult.success(result>0);
    }

    /**
     * 地面经轴入库列表
     */
    @GetMapping("/dmjzRkList")
    @Operation(description = "地面经轴入库列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult dmjzRkList(String date){
        Page.startPage();
        LambdaQueryWrapper<Bchb05dmjzcrk> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(date), Bchb05dmjzcrk::getBankingTime, date);
        wrapper.orderByDesc(Bchb05dmjzcrk::getBankingTime);
        List<Bchb05dmjzcrk> list = bchb05dmjzcrkMapper.selectList(wrapper);
        return Page.getDataTable(list);
    }

    /**
     * 地面经轴出库列表
     */
    @GetMapping("/dmjzCkList")
    @Operation(description = "地面经轴出库列表")
    @ApiResponse(content = @Content(
            schema = @Schema(anyOf = {AjaxResult.class})
    ))
    public AjaxResult dmjzCkList(String date){
        Page.startPage();
        LambdaQueryWrapper<Bchb05dmjzcrk> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(Bchb05dmjzcrk::getTimeOfRelease);
        wrapper.like(StringUtils.hasText(date), Bchb05dmjzcrk::getTimeOfRelease, date);
        wrapper.orderByDesc(Bchb05dmjzcrk::getTimeOfRelease);
        List<Bchb05dmjzcrk> list = bchb05dmjzcrkMapper.selectList(wrapper);
        return Page.getDataTable(list);
    }


    private String getName(){
        IPersonnelManagementDataSheetsService personnel = SpringUtil.getBean(IPersonnelManagementDataSheetsService.class);
        return personnel.getCorpMemberByLogin().getNick();
    }

}
